package net.lab1024.sa.gateway.processor;

import net.lab1024.sa.gateway.dto.ApiProcessDTO;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 限流处理器
 */
@Component
public class GlobalRateLimitProcessor extends AbstractApiProcessor {
    private final RedisRateLimiter redisRateLimiter;

    public GlobalRateLimitProcessor(RedisRateLimiter redisRateLimiter) {
        this.redisRateLimiter = redisRateLimiter;
    }

    @Override
    protected Mono<Void> doProcess(ApiProcessDTO dto) {
        String limitKey = dto.getDeviceFingerprint(); // 基于设备指纹限流
        return redisRateLimiter.isAllowed(limitKey, String.valueOf(1)) // 每次请求消耗1个令牌
                .flatMap(allow -> allow.isAllowed() ?
                        Mono.empty() :
                        Mono.error(new RuntimeException("RATE_LIMIT_EXCEEDED")));
    }
}